package com.netease.financial.base.login;

import android.annotation.TargetApi;
import android.app.ActionBar;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.ScrollView;
import android.widget.TextView;

import com.netease.financial.R;
import com.netease.financial.base.push.PushHelper;
import com.netease.financial.base.register.RegisterActivity;
import com.netease.financial.common.security.SecurityJNI;
import com.netease.financial.common.util.NfsLog;
import com.netease.financial.common.util.ToastUtils;
import com.netease.financial.domain.Factory;
import com.netease.financial.internal.di.components.DaggerLoginComponent;
import com.netease.financial.internal.di.components.LoginComponent;
import com.netease.financial.internal.di.modules.ActivityModule;
import com.netease.financial.internal.di.modules.LoginModule;
import com.netease.financial.ui.activity.BaseAppCompatActivity;

import javax.inject.Inject;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * A login screen that offers login via email/password.
 */
public class LoginActivity extends BaseAppCompatActivity implements LoginView {

    private static final String TAG = LoginActivity.class.getSimpleName();

    public static final String INTENT_EXTRA_KEY_CLIENT_ID = "clientId";
    public static final String INTENT_EXTRA_KEY_USER_ID = "userId";
    public static final String INTENT_EXTRA_KEY_ACCESS_TOKEN = "accessToken";

    public static final int REQUEST_CODE_FORGET_PASSWORD = 1;
    public static final int REQUEST_CODE_REGISTER = 2;

    @Bind(R.id.login_progress)
    ProgressBar loginProgress;
    @Bind(R.id.account_title)
    TextView accountTitle;
    @Bind(R.id.account)
    EditText account;
    @Bind(R.id.password_title)
    TextView passwordTitle;
    @Bind(R.id.password)
    EditText password;
    @Bind(R.id.password_indicator)
    ImageView passwordIndicator;
    @Bind(R.id.sign_in_button)
    Button signInButton;
    @Bind(R.id.forget_password)
    TextView forgetPassword;
    @Bind(R.id.register)
    TextView register;
    @Bind(R.id.account_login_form)
    LinearLayout emailLoginForm;
    @Bind(R.id.login_form)
    ScrollView loginForm;

    // UI references.
//    private EditText mEmailView;
//    private EditText mPasswordView;
//    private View mProgressView;
//    private View mLoginFormView;

    private String mClientId;
    private String mClientSecret;

    LoginComponent loginComponent;

    @Inject
    LoginPresenter loginPresenter;

    private class ClientId implements Factory<String> {

        @Override
        public String get() {
            return mClientId;
        }

    }

    private class ClientSecret implements Factory<String> {

        @Override
        public String get() {
            return mClientSecret;
        }

    }

    public static Intent getCallingIntent(Context context) {
        Intent intent = new Intent(context, LoginActivity.class);
        return intent;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        ButterKnife.bind(this);
        initialize();
    }

    private void initialize() {
        setupActionBar();
        initializeInjector();
        initializePresenter();
        initActionBar();
        initView();
    }

    private void initializeInjector() {
        this.loginComponent = DaggerLoginComponent.builder()
                .applicationComponent(getApplicationComponent())
                .activityModule(new ActivityModule(this))
                .loginModule(new LoginModule(new ClientId(), new ClientSecret(), SecurityJNI.getAppSecret()))
                .build();
        this.loginComponent.inject(this);
    }

    private void initializePresenter() {
        this.loginPresenter.setView(this);
        this.loginPresenter.initialize();
    }

    private void initActionBar() {
        enableLeftNavigationItem(true);
    }

    private void initView() {
        loginPresenter.refreshPageInfo();
        // Set up the login form.
//        mEmailView = (EditText) findViewById(R.id.client_id);
////        populateAutoComplete();
//
//        mPasswordView = (EditText) findViewById(R.id.password);
//        mPasswordView.setOnEditorActionListener(new TextView.OnEditorActionListener() {
//            @Override
//            public boolean onEditorAction(TextView textView, int id, KeyEvent keyEvent) {
//                if (id == R.id.login || id == EditorInfo.IME_NULL) {
////                    attemptLogin();
//                    return true;
//                }
//                return false;
//            }
//        });

//        Button mEmailSignInButton = (Button) findViewById(R.id.email_sign_in_button);
//        mEmailSignInButton.setOnClickListener(new OnClickListener() {
//            @Override
//            public void onClick(View view) {
////                attemptLogin();
//            }
//        });

//        mLoginFormView = findViewById(R.id.login_form);
//        mProgressView = findViewById(R.id.login_progress);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ButterKnife.unbind(this);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case REQUEST_CODE_FORGET_PASSWORD:
                    handleResetPasswordSuccessEvent(data);
                    return;
                case REQUEST_CODE_REGISTER:
                    handleLoginSuccessEvent(data);
                    return;
                default:
                    break;
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    private void handleLoginSuccessEvent(Intent data) {
        handleLoginSuccessEvent(data.getStringExtra(RegisterActivity.INTENT_EXTRA_KEY_CLIENT_ID),
                data.getStringExtra(RegisterActivity.INTENT_EXTRA_KEY_USER_ID),
                data.getStringExtra(RegisterActivity.INTENT_EXTRA_KEY_ACCESS_TOKEN));
    }

    private void handleLoginSuccessEvent(String clientId, String userId, String accessToken) {
        PushHelper.setAlias(this, userId);

        Intent intent = new Intent();
        intent.putExtra(INTENT_EXTRA_KEY_CLIENT_ID, clientId);
        intent.putExtra(INTENT_EXTRA_KEY_USER_ID, userId);
        intent.putExtra(INTENT_EXTRA_KEY_ACCESS_TOKEN, accessToken);

        setResult(RESULT_OK);
        finish();
    }

    private void handleResetPasswordSuccessEvent(Intent data) {
        //TODO
    }

    @OnClick(R.id.sign_in_button)
    void onLoginClick() {
        NfsLog.d(TAG, "onLoginClick");
        mClientId = account.getText().toString();
        mClientSecret = password.getText().toString();
        loginPresenter.login();
    }

    @OnClick(R.id.forget_password)
    void onForgetPasswordClick() {

    }

    @OnClick(R.id.register)
    void onRegisterClick() {
        getNavigator().navigateToRegisterScreen(this, REQUEST_CODE_REGISTER);
    }

    /**
     * Set up the {@link ActionBar}, if the API is available.
     */
    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    private void setupActionBar() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
            // Show the Up button in the action bar.
        }
    }

    private boolean isEmailValid(String email) {
        //TODO: Replace this with your own logic
        return email.contains("@");
    }

    private boolean isPasswordValid(String password) {
        //TODO: Replace this with your own logic
        return password.length() > 4;
    }

    /**
     * Shows the progress UI and hides the login form.
     */
    @TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
    private void showProgress(final boolean show) {
        // On Honeycomb MR2 we have the ViewPropertyAnimator APIs, which allow
        // for very easy animations. If available, use these APIs to fade-in
        // the progress spinner.
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
//            int shortAnimTime = getResources().getInteger(android.R.integer.config_shortAnimTime);
//
//            mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
//            mLoginFormView.animate().setDuration(shortAnimTime).alpha(
//                    show ? 0 : 1).setListener(new AnimatorListenerAdapter() {
//                @Override
//                public void onAnimationEnd(Animator animation) {
//                    mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
//                }
//            });
//
//            mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
//            mProgressView.animate().setDuration(shortAnimTime).alpha(
//                    show ? 1 : 0).setListener(new AnimatorListenerAdapter() {
//                @Override
//                public void onAnimationEnd(Animator animation) {
//                    mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
//                }
//            });
//        } else {
//            // The ViewPropertyAnimator APIs are not available, so simply show
//            // and hide the relevant UI components.
//            mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
//            mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
//        }
    }

    @Override
    public void showLoading() {
        showProgress(true);
    }

    @Override
    public void hideLoading() {
        showProgress(false);
    }

    @Override
    public void onError(String message) {
        ToastUtils.showShort(this, message);
    }

    @Override
    public void onSuccess(LoginViewModel loginViewModel) {
        handleLoginSuccessEvent(mClientId, loginViewModel.getAlias(), loginViewModel.getAccessToken());
    }

    @Override
    public void onSuccess(LoginPageViewModel loginPageViewModel) {

    }

    @Override
    public Context getContext() {
        return this;
    }
}

